// pagesCollect/pages/collect/list/list.js
import { listMyVillage } from "../../../../api/collect"
import { baseUrl } from "../../../../api/request"

const app = getApp()

const scroll = {
  page: 1,
  pagesize: 999,
  canLoad: true,
  listEnd: false,
  triggered: false,
}

Page({
  data: {
    scroll: JSON.parse(JSON.stringify(scroll)),
    list: [],
    navData: {
      title: '村镇列表',
      level: 10
    },
    navHeight: 32,
    navTop: 48,
  },
  onLoad() {
    this.setData({
      navHeight: app.globalData.navHeight, //导航栏高度
      navTop: app.globalData.navTop, //导航栏距顶部距离
    });
    this.refresh()
  },
  getlist() {
    if (!this.data.scroll.canLoad) {
      return false;
    }
    let { scroll, list } = this.data;
    scroll.canLoad = false;
    listMyVillage({
      pageNum: scroll.page,
      pageSize: scroll.pagesize
    }).then(res => {
      scroll.triggered = false;
      let newlist = res.data.rows;
      scroll.canLoad = true;

      newlist.forEach(item => {
        if (item.villageImage) {
          item.image = baseUrl + item.villageImage.split(',')[0];
        }
      })

      list = [
        ...list,
        ...newlist
      ]
      if (newlist.length < scroll.pagesize) {
        this.setData({
          ['scroll.listEnd']: true
        })
      } else {
        scroll.page++
      }
      this.setData({ list })
    }, function (err) {
      scroll.triggered = false;
      scroll.canLoad = true;
      this.setData({ list })
    })
  },
  refresh() {
    this.setData({
      scroll: JSON.parse(JSON.stringify(scroll)),
      list: []
    })
    this.getlist()
  },
  getMore() {
    // console.log(e)
    if (this.data.scroll.canLoad && !this.data.scroll.listEnd) {
      this.getlist()
    }
  },
  toclaim() {
    wx.navigateTo({
      url: '/pagesCollect/pages/collect/claim/claim',
    })
  },
  openInfo(e) {
    let index = e.currentTarget.dataset.index;
    let data = this.data.list[index];
    if (data.sums > 0) {
      this.toPrefect(e)
    } else {
      wx.navigateTo({
        url: '/pagesCollect/pages/collect/edit/village/village?id=' + data.villageId,
      })
    }

  },
  toPrefect(e) {
    let index = e.currentTarget.dataset.index;
    let data = this.data.list[index];
    wx.navigateTo({
      url: '/pagesCollect/pages/collect/perfect/perfect?id=' + data.villageId+'&name='+data.villageName,
    })
  },
  openMap(e) {
    let index = e.currentTarget.dataset.index;
    let data = this.data.list[index];
    if(!data.latitude||!data.longitude){
      wx.showToast({
        icon:'none',
        title: '暂无乡村坐标',
      })
      return false;
    }
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success(res) {
        const latitude = data.latitude
        const longitude = data.longitude
        wx.openLocation({
          latitude,
          longitude,
          scale: 18
        })
      }
    })
  }
})